package com.qanda.tools;

import com.qanda.data.entities.Korisnik;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class LocalDbAdapter {
	
private final Context context; 
    
    private LocalDbHelper DBHelper;
    private SQLiteDatabase db;
    
    public LocalDbAdapter(Context ctx)
    {
    	context=ctx;
    	DBHelper = new LocalDbHelper(context);
    }
    
  //---otvara se baza---
    public LocalDbAdapter open() throws SQLException 
    {
        db = DBHelper.getWritableDatabase();
        return this;
    }

    //---zatvara se baza---    
    public void close() 
    {
        DBHelper.close();
    }

  //---insert a title into the database---
    public long insertKorisnik(int id, String username, String pass, String uuid) 
    {
        ContentValues initialValues = new ContentValues();
        initialValues.put("id", id);
        initialValues.put("username", username);
        initialValues.put("pass", pass);
        initialValues.put("uuid", uuid);
        return db.insert("korisnik", null, initialValues);
    }
    
    public int updateInfoVerzija(int infoVerzija)
    {
    	ContentValues values=new ContentValues();
    	values.put("infoVerzija", infoVerzija);
    	return db.update("korisnik", values, null, null);
    }
    
  //---deletes a particular title---
    public boolean deleteKorisnik(int rowId) 
    {
    	this.open();
        long res = db.delete("korisnik", null, null) ;
        this.close();
        return res > 0;
    }
    
    public LocalKorisnik getKorisnik()
    {
    	this.open();
    	Cursor mCursor =
            db.query(true, "korisnik", new String[] {
            		"id",
            		"username", 
            		"pass",
            		"uuid",
            		"infoVerzija"
            		}, 
            		null,//ovde ide id=? 
            		null,
            		null, 
            		null, 
            		null, 
            		null);
    	
    if (mCursor != null && mCursor.getCount()>0) {
        mCursor.moveToFirst();
        
        LocalKorisnik k=new LocalKorisnik();
        k.setId(mCursor.getInt(0));
        k.setUuid(mCursor.getString(3));
        k.setUsername(mCursor.getString(1));
        k.setPass(mCursor.getString(2));
        int infoVerzija=0;
        try
        {
        	infoVerzija=mCursor.getInt(4);
        }catch(Exception ex){}
        
        k.setInfoVerzija(infoVerzija);
        this.close();
        return k;
    }
    else {this.close(); return null;}

    }


    
}
